package com.firemoss.atonement.messaging
{
	import com.firemoss.atonement.messaging.events.AtonementConsumerEvent;
	
	import flash.events.IEventDispatcher;
	
	import mx.messaging.Consumer;
	import mx.messaging.events.MessageEvent;
	
	public class AtonementConsumer extends Consumer
	{
		[Dispatcher]
		public var dispatcher : IEventDispatcher
		
		public var updateDelegates : Array = []
		
		public function AtonementConsumer(messageType:String="flex.messaging.messages.AsyncMessage")
		{
			super(messageType);
			
			dispatcher = this
				
			addEventListener( MessageEvent.MESSAGE, onMessageReceived, false, 0, true )
		}
		
		private function onMessageReceived( event : MessageEvent ) : void
		{
			var e : AtonementConsumerEvent = AtonementConsumerEvent.createEntityUpdateEvent( event.message.body.ENTITYNAME, event.message.body.ID )
				
			dispatcher.dispatchEvent( e );
			
			for each ( var updateDelegate : AtonementUpdateDelegate in updateDelegates )
			{
				if ( updateDelegate.entityName == event.message.body.ENTITYNAME )
				{
					updateDelegate.targetFunction.apply( null, [ event.message.body.ID ] );
				}
			}
		}
		
		
	}
}